package com.yizisu.library.ad.impl.ironsource

import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.ironsource.adapters.supersonicads.SupersonicConfig
import com.ironsource.mediationsdk.IronSource
import com.ironsource.mediationsdk.integration.IntegrationHelper
import com.weilele.mvvm.MvvmConf
import com.weilele.mvvm.mainHandler
import com.weilele.mvvm.utils.safeGet
import com.yizisu.library.ad.IAdRewardStatus
import com.yizisu.library.ad.IAdStatus
import com.yizisu.library.ad.impl.BaseAd
import com.yizisu.login.R

object IronSourceImpl : BaseAd() {
    init {
//        if (BU.isDebug) {
//            //广告日志
//            IronSource.setAdaptersDebug(true)
//            IronSource.setLogListener { ironSourceTag, s, i ->
//                logI { "ironSourceTag:${ironSourceTag.name},$s,$i" }
//            }
//        }
        //facebook广告缓存
        IronSource.setMetaData("Facebook_IS_CacheFlag", "IMAGE")
        SupersonicConfig.getConfigObj().clientSideCallbacks = true
        //奖励视频监听
        IronSource.setRewardedVideoListener(IronSourceVideoListener)
        //积分墙监听
        IronSource.setOfferwallListener(IronSourceOfferWallListener)
    }

    fun getInstance(activity: AppCompatActivity, uid: String?): IronSourceImpl {
//        if (MvvmConf.isDebug) {
//            //验证集成
//            IntegrationHelper.validateIntegration(activity)
//        }
        IronSource.init(
            activity,
            activity.getString(R.string.ironsource_app_key),
            IronSource.AD_UNIT.OFFERWALL,
//            IronSource.AD_UNIT.INTERSTITIAL,
//            IronSource.AD_UNIT.BANNER,
            IronSource.AD_UNIT.REWARDED_VIDEO
        )
        IronSource.setUserId(uid)
        activity.lifecycle.addObserver(this)
        return this
    }

    /**
     * 等待广告加载
     */
    private var waitVideoAdRunnable: Runnable? = null

    /**
     * 广告加载结果回调
     */
    private var waitVideoAdObserver: Observer<IAdStatus>? = null

    override fun showVideoAd(
        wait: Long,
        life: LifecycleOwner?,
        rewardListener: (IAdRewardStatus) -> Unit
    ): Boolean {
        //取消之前的等待，如果有
        cancelWaitVideoAd()
        if (IronSource.isRewardedVideoAvailable()) {//广告可用
            IronSourceVideoListener.rewardListener = rewardListener
            IronSource.showRewardedVideo()
            return true
        } else {//广告不可用
            if (wait >= 0 && life != null) {//等待加载，wait的等待的超时时间
                val run = Runnable {
                    checkVideoAd(rewardListener)
                    cancelWaitVideoAd()
                }
                waitVideoAdRunnable = run
                val observer = Observer<IAdStatus> {
                    if (it is IAdStatus.Success) {
                        waitVideoAdRunnable?.run()
                    }
                }
                waitVideoAdObserver = observer
                mainHandler.postDelayed(run, wait)
                IronSourceVideoListener.statusData.postValue(IAdStatus.Loading)
                IronSourceVideoListener.statusData.observe(life, observer)
            } else {
                rewardListener.invoke(IAdRewardStatus.NoAd)
            }
            return false
        }
    }

    override fun cancelWaitVideoAd() {
        waitVideoAdRunnable?.let {
            mainHandler.removeCallbacks(it)
        }
        waitVideoAdObserver?.let {
            IronSourceVideoListener.statusData.removeObserver(it)
        }
        waitVideoAdRunnable = null
        waitVideoAdObserver = null
    }

    private fun checkVideoAd(rewardListener: (IAdRewardStatus) -> Unit) {
        if (IronSource.isRewardedVideoAvailable()) {
            IronSourceVideoListener.rewardListener = rewardListener
            IronSource.showRewardedVideo()
        } else {
            rewardListener.invoke(IAdRewardStatus.NoAd)
        }
    }


    override fun showOfferWall(): Boolean {
        if (IronSource.isOfferwallAvailable()) {
            IronSource.showOfferwall()
            return true
        }
        return false
    }

    override fun getOfferWallCredits() {
        IronSource.getOfferwallCredits()
    }

    override fun setOnOfferWallListener(listener: ((Int, Int, Boolean) -> Boolean)?) {
        IronSourceOfferWallListener.offerWallListener = listener
        getOfferWallCredits()
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        owner.safeGet<Activity>()?.let {
            IronSource.onResume(it)
        }
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        owner.safeGet<Activity>()?.let {
            IronSource.onPause(it)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        cancelWaitVideoAd()
    }
}